using Unity.Burst;
using Unity.Entities;
using Unity.Scenes;

namespace DOTS.DOD.LESSON10
{
    [RequireMatchingQueriesForUpdate]
    [UpdateInGroup(typeof(EntityRespawnSystemGroup))]
    partial struct EntityRespawnSystem : ISystem, ISystemStartStop
    {
        int mIndex;
        float mTimer;
        Entity mPrefabLoaderEntity; //异步加载器
        Entity mInstanceEntity;

        [BurstCompile]
        public void OnCreate(ref SystemState state)
        {
            state.RequireForUpdate<RespawnController>();
        }

        [BurstCompile]
        public void OnUpdate(ref SystemState state)
        {
            if (!mPrefabLoaderEntity.Equals(default))
            {
                //异步加载完成
                if (state.EntityManager.HasComponent<PrefabLoadResult>(mPrefabLoaderEntity))
                {
                    //先销毁上一个
                    if (!mInstanceEntity.Equals(default))
                        state.EntityManager.DestroyEntity(mInstanceEntity);

                    //获取已经异步转完成的Entity
                    var prefabEntity = state.EntityManager.GetComponentData<PrefabLoadResult>(mPrefabLoaderEntity).PrefabRoot;
                    //实例化Entity
                    mInstanceEntity = state.EntityManager.Instantiate(prefabEntity);
                    
                    //重置加载器
                    state.EntityManager.DestroyEntity(mPrefabLoaderEntity);
                    mTimer = 0;
                }

                var controller = SystemAPI.GetSingleton<RespawnController>();
                mTimer += SystemAPI.Time.DeltaTime;
                if (mTimer >= controller.Timer) //开始加载下一个
                {
                    var spawners = SystemAPI.GetSingletonBuffer<PrefabBufferElement>(true);
                    //RequestEntityPrefabLoaded：异步加载Prefab
                    state.EntityManager.AddComponentData(mPrefabLoaderEntity, new RequestEntityPrefabLoaded()
                    {
                        Prefab = spawners[mIndex % spawners.Length].Prefab
                    });
                    mIndex++;
                    mTimer = 0f;
                }
            }
        }

        /// <summary>
        /// 开始运行时调用（类似OnEnable）
        /// </summary>
        [BurstCompile]
        public void OnStartRunning(ref SystemState state)
        {
            mIndex = 0;
            mTimer = 0f;
            mPrefabLoaderEntity = default;
            mInstanceEntity = default;

            mPrefabLoaderEntity = state.EntityManager.CreateEntity();
            var spawners = SystemAPI.GetSingletonBuffer<PrefabBufferElement>(true);
            //RequestEntityPrefabLoaded：异步加载Prefab
            state.EntityManager.AddComponentData(mPrefabLoaderEntity, new RequestEntityPrefabLoaded()
            {
                Prefab = spawners[mIndex % spawners.Length].Prefab
            });
            //RespawnCleanupComponent：销毁时只清除组件数据不销毁自身Entity和CleanupComponent
            state.EntityManager.AddComponent<RespawnCleanupComponent>(mPrefabLoaderEntity);
            mIndex++;
        }

        /// <summary>
        /// 结束运行时调用（类似OnDisable）
        /// </summary>
        [BurstCompile]
        public void OnStopRunning(ref SystemState state)
        {
            if (!mInstanceEntity.Equals(default))
            {
                state.EntityManager.DestroyEntity(mInstanceEntity);
                mInstanceEntity = default;
            }

            if (!mPrefabLoaderEntity.Equals(default))
            {
                state.EntityManager.DestroyEntity(mPrefabLoaderEntity);
                mIndex = 0;
                mTimer = 0f;
                mPrefabLoaderEntity = default;
            }
        }
    }
}